/*
* Use for spectrum annotation click events
*/
function atom_clicked(evt){
	var nodelabel = "";
	if (evt != null && evt.length > 0){
		nodelabel = evt[0]._private.data.label;
	}else{
		alert("Node ids are not populating, check table/db/cgi...");
		return;
	}
	
	var lmt = ","
	if ($("#spa_precursor_atoms_retained") != null){
		var pa_retained = $("#spa_precursor_atoms_retained").val();
		if (pa_retained == ""){
			lmt = "";
		}else{
			//if nodelabel is part of string, then deselect
			if (pa_retained.indexOf(nodelabel) != -1){
				var tk = pa_retained.split(",");
				for (var i = 0; i< tk.length; i++){
					if (nodelabel == tk[i]){
						var oval = pa_retained.replace(nodelabel, "");
						oval = oval.replace(",,", ",");
						if (oval.substring(0,1) == ","){
							oval = oval.substring(1,oval.length);
						}
						if (oval.substring(oval.length - 1,oval.length) == ","){
                                                        oval = oval.substring(0,oval.length-1);
                                                }
						$("#spa_precursor_atoms_retained").val(oval);
						var oc = element_color[nodelabel.replace(/[0-9]/g, "")];
						cy.$("#" + evt.id()).css("background-opacity", "1");
                                                cy.$("#" + evt.id()).css("border-color", oc);
						evt.unselect();
						return;
					}
				}
				//nodelabel.replace(/[0-9]/g, "");
			}
		
		}
		pa_retained = pa_retained + lmt + nodelabel;
		$("#spa_precursor_atoms_retained").val(pa_retained);
	}
	cy.$("#" + evt.id()).css("background-opacity", ".2");	
	cy.$("#" + evt.id()).css("border-color", "red");
	evt.unselect();
}

/*
load on ready for type ahead, ~40 compounds with sif defined
*/
function init_sifin(){
	$("#sifload_dialog").html("Loading... <img src='../images/demo_wait.gif' />");
	$("#status_label").html("Loading... <img src='../images/demo_wait.gif' />");
	var newSource = [];
        $.ajax({
        	type: "POST",
                url:  "/cgi-bin/get_compound_sif.cgi",
                data: {'search_input': null},
                success: function(json)
                {
			sif_dictionary  = $.parseJSON(json);
                        for (var jkey in sif_dictionary){
                        	newSource.push(sif_dictionary[jkey])
                        }
                        sifinTypeAhead.data('typeahead').source = newSource.sort();
			$("#sifload_dialog").hide();
			$("#status_label").html("");
                },
                error:function(xhr,err)
                {
                	alert("Failed loading sif\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                }
         });
}

/*
on load, check if combination of the two elements' atom transitions have been posted
*/
function visSifLoad(sifcontainer){
	//$("#sifload_dialog").html("Loading... <img src='../images/demo_wait.gif' />");
	$("#status_label").html("Loading... <img src='../images/demo_wait.gif' />");
	var val = $('#compound_sifin').val();
	var scid = null;
	if (sifcontainer != "#spa_structure_container"){
	    for (var jkey in sif_dictionary){
		if (sif_dictionary[jkey] == val){
			scid = jkey;
			break;
		}
	    }
	}else{
		scid = metabobase_session["pid"];
	}
	var spanlabel = "leftc_label";
	if (sifcontainer == "#cyleft"){
		$("#compound1_id").val(scid);
	}
	if (sifcontainer == "#cyright"){
		spanlabel = "rightc_label";
		$("#compound2_id").val(scid);
	}
	$('#' + spanlabel).html(val);
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/get_sif_def.cgi",
                data: {'compound_id': scid},
                success: function(json)
                        {
                                var csif = $.parseJSON(json)["csif"];
                                transformSif2jo(csif, sifcontainer);
        			if (sifcontainer != "#spa_structure_container"){
					$('#transitions_table').html(""); 
	 				var leftnodes = cy.nodes();
            				var rightnodes = rcy.nodes();
					var nodes_table = appendTransitionRows(leftnodes, rightnodes); 
					$('#transitions_table').html(nodes_table);             
					$("#status_label").html("");
				}
			},
                 error:function(xhr,err)
                       {
                                alert("Failed loading compound sif\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}

function visSifPost(){
        $("#status_label").html("Loading... <img src='../images/demo_wait.gif' />");
        var desc = $('#e2e_descriptionid').val();
	var c1id = $('#compound1_id').val();
	var c2id = $('#compound2_id').val();
        //get atom transitions - keep track on event change on hash
	var atom2atom = $('#atom2atom_id').val();
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/update_atom_transitions.cgi",
                data: {'compound_id_1': c1id, 'compound_id_2': c2id,'reaction_text': desc, 'atom2atom':atom2atom},
                success: function(json)
                        {
                                //var csif = $.parseJSON(json)["csif"];
                                $('#status_label').html("<th> " + $('#leftc_label').html() + " " +  $('#rightc_label').html() + " atom transactions saved</th>");
                        },
                 error:function(xhr,err)
                       {
                                alert("Failed updating atom transition\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                       }
        });
}

var element_color = {C:"black",O:"red",H:"white",P:"purple",S:"yellow"};

function transformSif2jo(sif_str, direction){
	var new_nodes = [];
	var new_links = [];
	var nodes_processed = {};
	var lines = sif_str.split("\n");
	var eid = 0;
	var directionid = "cid";
	if (direction == "#cyright")
		directionid = "gid";
	for (var l in lines){
		var tk = lines[l].split("\t");
		for (var t in tk){
			if (t != 1 && (nodes_processed[tk[t]] == undefined) && tk[t] != ""){
				var no = {};
				no.id = tk[t] + "_" + directionid;
				no.label = tk[t];
				//set color based on element?
				/*
				Carbon black
Nitrogen skyblue
Oxygen red
Hydrogen white
Phosporus purple
Sulfur yellow
Si and everything else = pink
*/
				var color = element_color[tk[t][0]];
				if (color == undefined)
					color = "pink";
				no.col = color;
				if (tk[t][0] == 'C'){
					no.lcolor = 'white';
				}
	                        new_nodes.push({"data":no});
				nodes_processed[tk[t]] = 1;
			}
			if (t > 1){
				if (tk[t] != ""){
					var eo = {};
                                	eo.id = "E" + eid + "_" + directionid;
                                	eo.source = tk[0] + "_"+ directionid;
					eid = eid + 1;
					eo.target = tk[t] + "_"+ directionid;
                        		new_links.push({"data":eo});
				}
			}
			//{ data: { id: "E0_cid", source: "C0_cid", target: "C1_cid"} },
		}
	}
	$(direction).html("");
	if (direction == "#cyright"){
		rcy = construct_plot_graph(direction, new_nodes, new_links);
	}else{
		cy = construct_plot_graph(direction, new_nodes, new_links);
	}
	$("#sifload_dialog").hide();
}

function markTElement(leftid, rightid){
        var right2element = $('#'+rightid).val().toUpperCase();
        if (rcy.$('#' + right2element + '_gid').element() == undefined){
		alert("Element " + right2element + " is not valid, try again.");
		$('#'+rightid).val("");
		return;
	}
	$('#'+rightid).val(right2element);
	rcy.$('#'+right2element + '_gid').css("background-opacity",".2");
        rcy.$('#'+right2element + '_gid').css("border-color","red");
        var left2element = $('#'+leftid).val();
        cy.$('#'+left2element + '_cid').css("background-opacity",".2");
        cy.$('#'+left2element + '_cid').css("border-color","red");
	var a2a = $("#atom2atom_id").val() + "," + left2element + ":" + right2element;
	$("#atom2atom_id").val(a2a);	
}

function appendTransitionRows(leftnodes, rightnodes){
    var end = leftnodes.length;
    if (rightnodes.length > end){
        end = rightnodes.length
    }
    var elerows = "<table>";
    for(i=0; i<end; i++){
            var leftinput = "";
            var rightinput = "";
            if (leftnodes[i] != undefined){
                leftinput = "<input size='6' readonly='true' id=le_" + leftnodes[i].data().id + " value=" + leftnodes[i].data().label + "></input>";
            }
            if (rightnodes[i] != undefined){
                var leftid = "null";
                if (leftnodes[i] != undefined){
                        leftid = leftnodes[i].data().id;
                }
                rightinput = "<input size='6' id=re_" + rightnodes[i].data().id + " value=''"
                //+ rightnodes[i].data().label
                + ' onchange="markTElement(\'le_' + leftid + '\', \'re_' + rightnodes[i].data().id +'\')"></input>';
            }
            elerows += '<tr><td>' + leftinput + ' </td> <td>&nbsp;<->&nbsp;' + rightinput + '</td></tr>';
//<input size="6" id="cinput_' + i + '" onchange="markTElement(\'cinput_' + i +'\')"></input></td></tr>';
    }

    return elerows + "</table>";
}

